'use strict';

import React, {Component, PropTypes} from 'react';
import {DateTimePicker, Input} from 'amazeui-react';

export default class DateTimeInput extends Component {
	/*
	 * 构造函数。
	 * @param props 属性
	 */
	constructor(props) {
		super(props);
		this.state = {
			pickerDisplay: 'none',
		};
	}

	/*
	 * 获取输入值。
	 * @return 输入值
	 */
	getValue() {
		return this.refs.input.getValue();
	}

	/*
	 * 获取输入值时间戳。
	 * @return 时间戳
	 */
	getTimestamp() {
		let value = this.refs.input.getValue();
		value = new Date(value).getTime();
		value /= 1000;

		return value;
	}

	/*
	 * 获得焦点时。
	 */
	handleFocus() {
		this.setState({
			pickerDisplay: 'block',
		});
	}

	/*
	 * 选择时。
	 * @param value 选择的日期时间
	 */
	handleSelect(value) {
		let input = this.refs.input.getFieldDOMNode();
		input.value = value;
		this.setState({
			pickerDisplay: 'none',
		});
		this.props.onSelect({
			value: this.getValue(),
			timestamp: this.getTimestamp(),
		});
	}

	/*
	 * 渲染。
	 */
	render() {
		return (
			<div style={{
				display: 'inline-block',
				width: this.props.width || '100%'
			}}>
				<Input
					type="text"
					onFocus={this.handleFocus.bind(this)}
					defaultValue={this.props.dateTime}
					ref="input"
					placeholder={this.props.placeholder}
				/>
				<DateTimePicker 
					onSelect={this.handleSelect.bind(this)}
					dateTime={this.props.dateTime}
					showTimePicker={this.props.showTimePicker}
					showDatePicker={this.props.showDatePicker}
					caretDisplayed={this.props.caretDisplayed}
					format={this.props.format}
					amStyle={this.props.amStyle}
					viewMode={this.props.viewMode}
					minViewMode={this.props.minViewMode}
					daysOfWeekDisabled={this.props.daysOfWeekDisabled}
					locale={this.props.locale}
					minDate={this.props.minDate}
					maxDate={this.props.maxDate}
					style={{
						display: this.state.pickerDisplay,
						position: 'absolute',
						zIndex: 999
					}}
				/>
			</div>
		);
	}
}

DateTimeInput.propTypes = {
	dateTime: PropTypes.string,
	showTimePicker: PropTypes.bool,
	showDatePicker: PropTypes.bool,
	caretDisplayed: PropTypes.bool,
	format: PropTypes.string,
	amStyle: PropTypes.oneOf(['success','warning','danger']),
	viewMode: PropTypes.oneOf(['days','months','years']),
	minViewMode: PropTypes.oneOf(['days','months','years']),
	daysOfWeekDisabled: PropTypes.array,
	locale: PropTypes.string,
	minDate: PropTypes.string,
	maxDate: PropTypes.string,
	placeholder: PropTypes.string,
	onSelect: PropTypes.func,
	width: PropTypes.number
};
DateTimeInput.defaultProps = {
	locale: 'zh-CN',
	caretDisplayed: false,
	onSelect: value => {},
};
